import React, { useState } from "react";
import "./login.less";
import { Button, Checkbox, Form, Input, Radio } from "antd";
import { useNavigate } from "react-router-dom";
import { reqLogin } from "@/api/api";
import { debounce } from "@/tool/debounce";


export default function Login() {
  
  const [form] = Form.useForm();
  const [userRole, setUserRole] = useState("student");
  const [error, setError] = useState("")
  const navigate = useNavigate();
  
  const [formInfor,setFormInfor] = useState({
    remember:JSON.parse(window.localStorage.getItem("role"))?.remember,
    username:JSON.parse(window.localStorage.getItem("role"))?.username,
    password:JSON.parse(window.localStorage.getItem("role"))?.password
  })
  
 console.log('formInfor', formInfor)


  const authority = [
    { label: '学生', value: 'student' },
    { label: '教师', value: 'teacher' },
  ]
  
  const sendConst = (values) =>{
    const { username, password,remember } = values
    if(remember){
      window.localStorage.setItem("role",JSON.stringify({username,password,remember}))
    }else{
      window.localStorage.removeItem("role")
    }

    reqLogin({ username, password, userRole }).then(
      res => {
        if (res.status === 200) {
          window.sessionStorage.setItem("role", JSON.stringify(res.data))
          navigate('/home',{replace:true})
        }
        console.log(res);
        setError(res.data)
      },
      rej => {
        setError(rej.response)
      }
    )
  }
  // 发送请求
  const onFinish = (values) => debounce(sendConst(values),200)
  
  
  const onFinishFailed = (errorInfo) => {
    setError(errorInfo?.errorFields[0].errors)
    form.resetFields(); 
  };

  // 用户密码校验
  const checkValues = async (_, value) => {
    let checkValue = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
    let name = _.field === "username" ? '用户名' : '密码'
    if (checkValue.test(value)) {
      return Promise.reject(`${name}包含特殊字符`)
    }
    if(value === undefined){
      return Promise.reject(`没有${name}就登录`)
    }
    return Promise.resolve()
  }

  return (
    <div className="login-back">
      <div className="login-form">
        <h1>西城教务系统</h1>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 15 }}
          initialValues={{
            ...formInfor
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          onFieldsChange={() => { setError("") }}
          >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ validator: checkValues },]}
            >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            colon
            rules={[{ validator: checkValues },]}
            >
            <Input.Password />
          </Form.Item>

          <Form.Item
            wrapperCol={{ span: 16, offset: 5 }}
            className="ant-row-role"
            >
            <Radio.Group 
              options={authority} 
              onChange={({ target: { value } }) => setUserRole(value)} 
              value={userRole} 
              />
            {error && <div style={{ color: 'red' }}>{error}</div>}
          </Form.Item>

          <Form.Item wrapperCol={{offset: 11, span: 16 }}>
            <Button type="primary" htmlType="submit" style={{ borderRadius: "10px" }}>
              登录
            </Button>
          </Form.Item>

          <Form.Item
            name="remember"
            valuePropName="checked"
            wrapperCol={{ offset: 16,span: 7}}
            >
            <Checkbox>记住密码</Checkbox>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
